package gbackup.main;

import gbackup.core.GBackupService;
import gbackup.core.Shell;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.google.gdata.client.docs.DocsService;
import com.google.gdata.util.AuthenticationException;


public class ConsoleBasedGBackup implements GBackupService {
	private static final String VERSION = "OpenPen-ConsoleBasedGBackup-1.0";
	private Shell _shell = null;
	private String _username = null;
	private String _password = null;

	public ConsoleBasedGBackup() {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		System.out.print("Username: ");
		System.out.flush();
		try {
			this._username = br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		MaskingThread mt = new MaskingThread("Password: ");
		mt.start();
		try {
			this._password = br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		} finally {
			mt.stopMasking();
		}
	}

	@Override
	public void startService() {
		DocsService client = new DocsService(VERSION);

		try {
			client.setUserCredentials(this._username + "@gmail.com", this._password);
		} catch (AuthenticationException e) {
			System.out.println("Error: Login Failure");
			System.exit(-1);
		}

		this._shell = new PShell(this, client, System.in, System.out);
		this._shell.start();
	}

	@Override
	public void stopService() {
		this._shell.stop();
		this._shell = null;
	}

	@Override
	public void restartService() {
		this.stopService();
		this.startService();
	}

	public static void main(String[] argv) {
		new ConsoleBasedGBackup().startService();
	}

	private class MaskingThread extends Thread {
		private volatile boolean _stop;
		private char _echochar = ' ';

		public MaskingThread(String prompt) {
			System.out.print(prompt);
		}

		public void run() {
			int priority = Thread.currentThread().getPriority();
			Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

			try {
				this._stop = true;
				while (this._stop) {
					System.out.print("\010" + this._echochar);
					try {
						Thread.sleep(1);
					} catch (InterruptedException iex) {
						Thread.currentThread().interrupt();
						return;
					}
				}
			} finally {
				Thread.currentThread().setPriority(priority);
			}
		}

		public void stopMasking() {
			this._stop = false;
		}
	}
}